<template>
  <div class="file-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="queryParams.fileName"
              placeholder="请输入文件名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="queryParams.fileType" placeholder="文件类型" clearable>
              <el-option label="图片" value="image" />
              <el-option label="文档" value="document" />
              <el-option label="视频" value="video" />
              <el-option label="音频" value="audio" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="上传时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-upload" @click="handleUpload">上传文件</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-download" :disabled="single" @click="handleDownload">下载</el-button>
      <el-dropdown split-button type="primary" @click="handleViewMode('table')" class="view-mode-dropdown">
        <span>{{ viewMode === 'table' ? '表格视图' : '卡片视图' }}</span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleViewMode('table')">表格视图</el-dropdown-item>
            <el-dropdown-item @click="handleViewMode('card')">卡片视图</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    
    <!-- 表格视图 -->
    <el-card class="table-card" v-if="viewMode === 'table'">
      <el-table
        v-loading="loading"
        :data="fileList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="file-name-cell">
              <i :class="getFileIcon(scope.row.fileType)" class="file-icon"></i>
              <span class="file-name" @click="handlePreview(scope.row)">{{ scope.row.fileName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="文件类型" align="center" prop="fileType" width="100">
          <template #default="scope">
            <el-tag :type="getFileTagType(scope.row.fileType)">{{ getFileTypeName(scope.row.fileType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传人员" align="center" prop="createBy" width="100" />
        <el-table-column label="上传时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-view" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 卡片视图 -->
    <div class="card-view" v-else>
      <el-card class="table-card">
        <el-empty v-if="fileList.length === 0" description="暂无文件数据" />
        <div class="file-cards">
          <div 
            v-for="(item, index) in fileList" 
            :key="index" 
            class="file-card"
            @click="handleCardClick(item)"
          >
            <div class="file-card-header">
              <div class="file-type-icon">
                <i :class="getFileIcon(item.fileType)"></i>
              </div>
              <el-checkbox 
                v-model="item.selected" 
                @click.stop 
                @change="handleCardSelect(item)"
              ></el-checkbox>
            </div>
            <div class="file-card-content">
              <div class="file-card-name" :title="item.fileName">{{ item.fileName }}</div>
              <div class="file-card-info">
                <span>{{ formatFileSize(item.fileSize) }}</span>
                <span>{{ item.createTime }}</span>
              </div>
            </div>
            <div class="file-card-actions">
              <el-button type="text" icon="el-icon-view" @click.stop="handlePreview(item)">预览</el-button>
              <el-button type="text" icon="el-icon-download" @click.stop="handleDownload(item)">下载</el-button>
              <el-button type="text" icon="el-icon-delete" @click.stop="handleDelete(item)">删除</el-button>
            </div>
          </div>
        </div>
        
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
    </div>
    
    <!-- 上传文件对话框 -->
    <el-dialog title="上传文件" v-model="uploadOpen" width="500px" append-to-body>
      <el-upload
        class="upload-container"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="uploadFileList"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            支持任意类型文件，单个文件大小不超过100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpload">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 文件预览对话框 -->
    <el-dialog :title="previewTitle" v-model="previewOpen" width="800px" append-to-body>
      <div class="preview-container">
        <!-- 图片预览 -->
        <div v-if="previewFile.fileType === 'image'" class="image-preview">
          <img :src="previewFile.fileUrl" alt="预览图片" />
        </div>
        
        <!-- 文档预览 -->
        <div v-else-if="previewFile.fileType === 'document'" class="document-preview">
          <div class="document-preview-placeholder">
            <i class="el-icon-document"></i>
            <p>暂不支持在线预览文档，请下载后查看</p>
            <el-button type="primary" @click="handleDownload(previewFile)">下载文件</el-button>
          </div>
        </div>
        
        <!-- 视频预览 -->
        <div v-else-if="previewFile.fileType === 'video'" class="video-preview">
          <video controls :src="previewFile.fileUrl" class="video-player"></video>
        </div>
        
        <!-- 音频预览 -->
        <div v-else-if="previewFile.fileType === 'audio'" class="audio-preview">
          <audio controls :src="previewFile.fileUrl" class="audio-player"></audio>
        </div>
        
        <!-- 其他文件 -->
        <div v-else class="other-preview">
          <div class="other-preview-placeholder">
            <i class="el-icon-document"></i>
            <p>无法预览此类型文件，请下载后查看</p>
            <el-button type="primary" @click="handleDownload(previewFile)">下载文件</el-button>
          </div>
        </div>
        
        <!-- 文件信息 -->
        <div class="file-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="文件名称">{{ previewFile.fileName }}</el-descriptions-item>
            <el-descriptions-item label="文件大小">{{ formatFileSize(previewFile.fileSize) }}</el-descriptions-item>
            <el-descriptions-item label="文件类型">{{ getFileTypeName(previewFile.fileType) }}</el-descriptions-item>
            <el-descriptions-item label="上传时间">{{ previewFile.createTime }}</el-descriptions-item>
            <el-descriptions-item label="上传人员">{{ previewFile.createBy }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
          <el-button type="primary" @click="handleDownload(previewFile)">下 载</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 文件表格数据
const fileList = ref([])
// 日期范围
const dateRange = ref([])
// 视图模式：table 或 card
const viewMode = ref('table')

// 上传相关变量
const uploadOpen = ref(false)
const uploadFileList = ref([])

// 预览相关变量
const previewOpen = ref(false)
const previewTitle = ref('文件预览')
const previewFile = reactive({
  fileName: '',
  fileSize: 0,
  fileType: '',
  fileUrl: '',
  createBy: '',
  createTime: ''
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  fileName: undefined,
  fileType: undefined
})

// 模拟数据
const mockFileList = [
  {
    id: 1,
    fileName: '项目需求文档.docx',
    fileSize: 1024 * 1024 * 2.5, // 2.5MB
    fileType: 'document',
    fileUrl: 'https://example.com/files/1',
    createBy: 'admin',
    createTime: '2023-05-20 14:30:00',
    selected: false
  },
  {
    id: 2,
    fileName: '系统架构图.png',
    fileSize: 1024 * 1024 * 1.2, // 1.2MB
    fileType: 'image',
    fileUrl: 'https://example.com/files/2',
    createBy: 'admin',
    createTime: '2023-05-19 10:15:00',
    selected: false
  },
  {
    id: 3,
    fileName: '操作演示视频.mp4',
    fileSize: 1024 * 1024 * 15, // 15MB
    fileType: 'video',
    fileUrl: 'https://example.com/files/3',
    createBy: 'admin',
    createTime: '2023-05-18 16:45:00',
    selected: false
  },
  {
    id: 4,
    fileName: '会议记录.txt',
    fileSize: 1024 * 10, // 10KB
    fileType: 'document',
    fileUrl: 'https://example.com/files/4',
    createBy: 'user',
    createTime: '2023-05-17 09:30:00',
    selected: false
  },
  {
    id: 5,
    fileName: '产品宣传片.mp3',
    fileSize: 1024 * 1024 * 5.8, // 5.8MB
    fileType: 'audio',
    fileUrl: 'https://example.com/files/5',
    createBy: 'user',
    createTime: '2023-05-16 11:20:00',
    selected: false
  }
]

// 查询文件列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    fileList.value = mockFileList.map(item => ({...item, selected: false}))
    total.value = mockFileList.length
    loading.value = false
  }, 500)
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.fileName = undefined
  queryParams.fileType = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 卡片选择
const handleCardSelect = (item) => {
  // 更新选中状态
  const selectedIds = fileList.value
    .filter(file => file.selected)
    .map(file => file.id)
  
  ids.value = selectedIds
  single.value = selectedIds.length !== 1
  multiple.value = !selectedIds.length
}

// 卡片点击
const handleCardClick = (item) => {
  item.selected = !item.selected
  handleCardSelect(item)
}

// 切换视图模式
const handleViewMode = (mode) => {
  viewMode.value = mode
}

// 上传按钮操作
const handleUpload = () => {
  uploadFileList.value = []
  uploadOpen.value = true
}

// 文件变更处理
const handleFileChange = (file, fileList) => {
  uploadFileList.value = fileList
}

// 提交上传
const submitUpload = () => {
  if (uploadFileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  // 模拟上传
  ElMessage.success(`成功上传 ${uploadFileList.value.length} 个文件`)
  uploadOpen.value = false
  getList()
}

// 取消上传
const cancelUpload = () => {
  uploadOpen.value = false
  uploadFileList.value = []
}

// 预览按钮操作
const handlePreview = (row) => {
  Object.assign(previewFile, row)
  previewTitle.value = `文件预览 - ${row.fileName}`
  previewOpen.value = true
}

// 下载按钮操作
const handleDownload = (row) => {
  const fileId = row?.id || ids.value[0]
  // 模拟下载
  ElMessage.success(`开始下载: ${row ? row.fileName : '选中文件'}`)
}

// 删除按钮操作
const handleDelete = (row) => {
  const fileIds = row?.id ? [row.id] : ids.value
  const fileNames = row?.fileName ? [row.fileName] : fileList.value
    .filter(item => fileIds.includes(item.id))
    .map(item => item.fileName)
  
  ElMessageBox.confirm(`确认删除以下文件吗?<br/>${fileNames.join('<br/>')}`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 获取文件图标
const getFileIcon = (fileType) => {
  switch (fileType) {
    case 'image':
      return 'el-icon-picture'
    case 'document':
      return 'el-icon-document'
    case 'video':
      return 'el-icon-video-camera'
    case 'audio':
      return 'el-icon-headset'
    default:
      return 'el-icon-document'
  }
}

// 获取文件类型名称
const getFileTypeName = (fileType) => {
  switch (fileType) {
    case 'image':
      return '图片'
    case 'document':
      return '文档'
    case 'video':
      return '视频'
    case 'audio':
      return '音频'
    default:
      return '其他'
  }
}

// 获取文件标签类型
const getFileTagType = (fileType) => {
  switch (fileType) {
    case 'image':
      return 'success'
    case 'document':
      return 'primary'
    case 'video':
      return 'warning'
    case 'audio':
      return 'info'
    default:
      return 'info'
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.file-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.view-mode-dropdown {
  margin-left: auto;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

/* 表格视图样式 */
.file-name-cell {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  font-size: 18px;
}

.file-name {
  color: #409EFF;
  cursor: pointer;
}

.file-name:hover {
  text-decoration: underline;
}

/* 卡片视图样式 */
.file-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px 0;
}

.file-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  height: 180px;
  display: flex;
  flex-direction: column;
}

.file-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #d9ecff;
  background-color: #f5f7fa;
}

.file-card-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.file-type-icon {
  font-size: 32px;
  color: #909399;
}

.file-type-icon .el-icon-picture {
  color: #67C23A;
}

.file-type-icon .el-icon-document {
  color: #409EFF;
}

.file-type-icon .el-icon-video-camera {
  color: #E6A23C;
}

.file-type-icon .el-icon-headset {
  color: #F56C6C;
}

.file-card-content {
  padding: 0 16px;
  flex: 1;
}

.file-card-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.file-card-info {
  font-size: 12px;
  color: #909399;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.file-card-actions {
  padding: 8px 16px;
  border-top: 1px solid #EBEEF5;
  display: flex;
  justify-content: space-around;
}

/* 上传容器样式 */
.upload-container {
  width: 100%;
}

/* 预览容器样式 */
.preview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.image-preview {
  display: flex;
  justify-content: center;
  max-height: 400px;
  overflow: auto;
}

.image-preview img {
  max-width: 100%;
  object-fit: contain;
}

.document-preview, .other-preview {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.document-preview-placeholder, .other-preview-placeholder {
  text-align: center;
}

.document-preview-placeholder i, .other-preview-placeholder i {
  font-size: 64px;
  color: #909399;
  margin-bottom: 16px;
}

.video-preview, .audio-preview {
  display: flex;
  justify-content: center;
}

.video-player {
  width: 100%;
  max-height: 400px;
}

.audio-player {
  width: 100%;
}

.file-info {
  margin-top: 20px;
}
</style> 